package com.android.fragmentdemo.service
import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import com.android.fragmentdemo.defineviews.MonitorView
import com.hengfoxwolf.commonbase.base.util.LogX

//无障碍服务,可以用来监控系统相关按键事件
class MonitorService : AccessibilityService() {
    /*
    * 开启无障碍服务方式
    * 一:跳转到无障碍服务页面去开启
    *   val serviceIntent =  Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
    *   serviceIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    *   startActivity(serviceIntent)
    *
    * 二:通过adb命令开启android.permission.WRITE_SECURE_SETTINGS权限  然后自动开启
    *   1)执行adb命令  adb shell pm grant 应用包名 android.permission.WRITE_SECURE_SETTINGS
    *   2)
    *    Settings.Secure.putString(this.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "应用包名/自定义无障碍服务全名称")
    *    Settings.Secure.putInt(this.contentResolver, Settings.Secure.ACCESSIBILITY_ENABLED, 1)
    *
    * 开启后会自动回调onCreate()、onServiceConnected()方法
    * */

    private var mWindowManager: WindowManager? = null
    private var wmLayoutParams: WindowManager.LayoutParams? = null

    private var mMonitorView: MonitorView? = null

    override fun onCreate() {
        super.onCreate()
        //服务创建时调用
        Log.d(TAG, "override fun onCreate()")
        showWindow()

    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        //服务连接时调用
        Log.d(TAG, "override fun onServiceConnected()")

    }

    override fun onKeyEvent(event: KeyEvent?): Boolean {
        when (event?.action) {
            KeyEvent.ACTION_DOWN -> {
                when (event.keyCode) {
                    KeyEvent.KEYCODE_BACK -> {
                        //返回
                    }
                    KeyEvent.KEYCODE_BUTTON_B -> {
                        //按键B
                    }
                    KeyEvent.KEYCODE_HOME -> {
                        //home键
                    }
                }
            }
            KeyEvent.ACTION_UP -> {
                when (event.keyCode) {
                    KeyEvent.KEYCODE_BACK -> {
                        //返回
                    }
                    KeyEvent.KEYCODE_BUTTON_B -> {
                        //按键B
                    }
                    KeyEvent.KEYCODE_HOME -> {
                        //home键
                    }
                }
            }
        }
        return false
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        LogX.d(TAG, "override fun onAccessibilityEvent---${event?.eventType}")
        when (event?.eventType) {
            /*AccessibilityEvent.TYPE_VIEW_CLICKED -> {
                //View点击
            }
            AccessibilityEvent.TYPE_WINDOWS_CHANGED -> {}
            AccessibilityEvent.TYPE_ANNOUNCEMENT -> {}
            AccessibilityEvent.TYPE_ASSIST_READING_CONTEXT -> {}
            AccessibilityEvent.TYPE_GESTURE_DETECTION_END -> {}
            AccessibilityEvent.TYPE_GESTURE_DETECTION_START -> {}
            AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> {}
            AccessibilityEvent.TYPE_SPEECH_STATE_CHANGE -> {}
            AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END -> {}
            AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START -> {}
            AccessibilityEvent.TYPE_TOUCH_INTERACTION_END -> {}
            AccessibilityEvent.TYPE_TOUCH_INTERACTION_START -> {}
            AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED -> {}
            AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED -> {}
            AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED -> {}
            AccessibilityEvent.TYPE_VIEW_FOCUSED -> {}
            AccessibilityEvent.TYPE_VIEW_HOVER_ENTER -> {}
            AccessibilityEvent.TYPE_VIEW_HOVER_EXIT -> {}
            AccessibilityEvent.TYPE_VIEW_LONG_CLICKED -> {}
            AccessibilityEvent.TYPE_VIEW_SCROLLED -> {}
            AccessibilityEvent.TYPE_VIEW_SELECTED -> {}
            AccessibilityEvent.TYPE_VIEW_TARGETED_BY_SCROLL -> {}
            AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED -> {}
            AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED -> {}
            AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY -> {}
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {}*/
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                //窗口改变
                //获取到顶部活动的类名，进而执行相关的操作。
                val clazzName = event.className
                LogX.d(TAG, "clazzName:${clazzName}")
            }
        }
    }

    override fun onInterrupt() {
        //service被中断时调用

    }

    override fun onDestroy() {
        super.onDestroy()
        hideWindow()
    }

    private fun showWindow() {
        if (mWindowManager == null) {
            mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            mMonitorView = MonitorView(this, null)
        }

        wmLayoutParams = WindowManager.LayoutParams(
            1,
            1,
            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
            PixelFormat.TRANSLUCENT
        )

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //8.0+,不设置这个flag可能会报错
            wmLayoutParams!!.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            wmLayoutParams!!.type = WindowManager.LayoutParams.TYPE_PHONE
        }

        wmLayoutParams!!.format = PixelFormat.RGBA_4444
        mWindowManager?.addView(mMonitorView, wmLayoutParams)
    }

    private fun hideWindow() {
        mWindowManager?.removeView(mMonitorView)
    }

    private fun updateWindow() {
        wmLayoutParams?.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        mWindowManager?.updateViewLayout(mMonitorView, wmLayoutParams)
    }

    companion object {
        const val TAG = "MonitorService"
    }
}